package com.blrs.service.process.impl;

import com.blrs.common.exception.ServiceException;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.uuid.UUID;
import com.blrs.domain.Stage;
import com.blrs.mapper.ProcessStageMapper;
import com.blrs.mapper.StageMapper;
import com.blrs.service.process.IStageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StageServiceImpl implements IStageService {

    @Autowired
    private StageMapper stageMapper;

    @Autowired
    private ProcessStageMapper processStageMapper;

    @Override
    public List<Stage> selectStageList(Stage stage) {
        stage.setBelongTo(SecurityUtils.getOrgId());
        return stageMapper.selectStageList(stage);
    }

    @Override
    public Stage selectStageById(String id) {
        return stageMapper.selectStageById(id);
    }

    @Override
    public int insertStage(Stage stage) {
        stage.setId(UUID.randomUUID().toString());
        stage.setBelongTo(SecurityUtils.getOrgId());
        stage.setCreateBy(SecurityUtils.getUsername());
        if (!checkStageNameUnique(stage)) {
            throw new ServiceException("阶段名称'" + stage.getStageName() + "'已存在");
        }
        return stageMapper.insertStage(stage);
    }

    @Override
    public int updateStage(Stage stage) {
        if (!checkStageNameUnique(stage)) {
            throw new ServiceException("阶段名称'" + stage.getStageName() + "'已存在");
        }
        return stageMapper.updateStage(stage);
    }

    @Override
    public int deleteStageByIds(String[] ids) {
        Integer count = processStageMapper.checkStageInUse(ids[0]);
        if (count > 0) {
            throw new ServiceException("该阶段已被流程模板使用，无法删除");
        }
        return stageMapper.deleteStageByIds(ids);
    }

    /**
     * 校验阶段名称是否唯一
     *
     * @param stage 阶段信息
     * @return 结果
     */
    @Override
    public boolean checkStageNameUnique(Stage stage) {
        String id = stage.getId() == null ? "" : stage.getId();
        Stage info = stageMapper.checkStageNameUnique(stage.getStageName(), id,SecurityUtils.getOrgId());
        return info == null || info.getId().equals(id);
    }

    @Override
    public int deleteStageByIdsFromProcess(String[] ids) {
        return processStageMapper.deleteProcessStageByStageIds(ids);
    }
} 